package com.innovation.ic.im.end.base.handler.im_erp9;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.innovation.ic.im.end.base.model.im_erp9.*;
import com.innovation.ic.im.end.base.pojo.constant.MessageType;
import com.innovation.ic.im.end.base.pojo.enums.AvailableStatusEnum;
import com.innovation.ic.im.end.base.pojo.enums.ReadStatusEnum;
import com.innovation.ic.im.end.base.pojo.im_erp9.TreeNodePojo;
import com.innovation.ic.im.end.base.vo.im_erp9.GroupMessageVo;
import com.innovation.ic.im.end.base.vo.im_erp9.MessageVo;
import com.innovation.ic.im.end.base.vo.im_erp9.UserGroupMessageVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * 消息对象转换类
 */
@Component
public class ModelHandler extends ImErp9AbstractHandler {

    /**
     * 将JSONObject对象转换为GroupMessage类型对象，JSONObject是从数据库中取出的格式（下划线）
     *
     * @param jsonObject
     * @return
     */
    public GroupMessage toGroupMessageFromTableFormat(JSONObject jsonObject) {
        GroupMessage groupMessage = new GroupMessage();
        groupMessage.setId(jsonObject.getInteger("id"));
        groupMessage.setGroupId(jsonObject.getString("group_id"));
        groupMessage.setFromUserAccount(jsonObject.getString("from_user_account"));
        groupMessage.setFromUserRealName(jsonObject.getString("from_user_real_name"));
        groupMessage.setContent(jsonObject.getString("content"));
        groupMessage.setType(jsonObject.getInteger("type_"));
        groupMessage.setFilePath(jsonObject.getString("file_path"));
        groupMessage.setFromUserAvailable(jsonObject.getInteger("from_user_available"));
        groupMessage.setFromUserUnavailableTime(jsonObject.getDate("from_user_unavailable_time"));
        groupMessage.setCreateTime(jsonObject.getDate("create_time"));
        groupMessage.setRetractionTime(jsonObject.getDate("retraction_time"));
        groupMessage.setRetractionContent(jsonObject.getString("retraction_content"));
        return groupMessage;
    }

    /**
     * 将GroupMessageVo对象转换为GroupMessage对象
     *
     * @param groupMessageVo
     * @return
     */
    public GroupMessage toGroupMessage(GroupMessageVo groupMessageVo) {
        return new GroupMessage(null, groupMessageVo.getGroupId(), groupMessageVo.getFromUserAccount(), groupMessageVo.getContent(), groupMessageVo.getType(),
                groupMessageVo.getFilePath(), groupMessageVo.getFromUserRealName(), null, null, AvailableStatusEnum.AVAILABLE.getCode(), null);
    }

    /**
     * 将Set<String>类型对象转换为List<GroupMessage>类型对象
     *
     * @param stringSet
     * @return
     */
    public List<GroupMessage> toGroupMessageList(Set<String> stringSet, String fromUserAccount) {
        List<GroupMessage> groupMessageList = new ArrayList<>();
        Iterator<String> iterator = stringSet.iterator();
        while (iterator.hasNext()) {
            String str = iterator.next();
            JSONObject jsonObject = JSON.parseObject(str);
            GroupMessage groupMessage = JSON.parseObject(String.valueOf(jsonObject), GroupMessage.class);
            if (fromUserAccount.equals(groupMessage.getFromUserAccount()) && groupMessage.getType().intValue() == MessageType.SYS_MSG.intValue()) {
                String content = groupMessage.getContent();
                content = content.replaceAll(groupMessage.getFromUserRealName(), "你");
                groupMessage.setContent(content);
            }
            groupMessageList.add(groupMessage);
        }
        return groupMessageList;
    }

    /**
     * 将JSONObject对象转换为Message类型对象，JSONObject是从数据库中取出的格式（下划线）
     *
     * @param jsonObject
     * @return
     */
    public Message toMessageFromTableFormat(JSONObject jsonObject) {
        Message message = new Message();
        message.setId(jsonObject.getInteger("id"));
        message.setFromUserAccount(jsonObject.getString("from_user_account"));
        message.setToUserAccount(jsonObject.getString("to_user_account"));
        message.setContent(jsonObject.getString("content"));
        message.setType(jsonObject.getInteger("type_"));
        message.setFilePath(jsonObject.getString("file_path"));
        message.setFromUserRealName(jsonObject.getString("from_user_real_name"));
        message.setToUserRealName(jsonObject.getString("to_user_real_name"));
        message.setRead(jsonObject.getInteger("read_"));
        message.setReadTime(jsonObject.getDate("read_time"));
        message.setFromUserAvailable(jsonObject.getInteger("from_user_available"));
        message.setFromUserUnavailableTime(jsonObject.getDate("from_user_unavailable_time"));
        message.setToUserAvailable(jsonObject.getInteger("to_user_available"));
        message.setToUserUnavailableTime(jsonObject.getDate("to_user_unavailable_time"));
        message.setCreateTime(jsonObject.getDate("create_time"));
        message.setRetractionTime(jsonObject.getDate("retraction_time"));
        message.setRetractionContent(jsonObject.getString("retraction_content"));
        return message;
    }

    /**
     * 将MessageVo对象转换为Message对象
     *
     * @param messageVo
     * @return
     */
    public Message toMessage(MessageVo messageVo) {
        return new Message(null, messageVo.getFromUserAccount(), messageVo.getToUserAccount(), messageVo.getContent(), messageVo.getType(), messageVo.getFilePath(), ReadStatusEnum.UN_READ.getCode(), null,
                AvailableStatusEnum.AVAILABLE.getCode(), null, AvailableStatusEnum.AVAILABLE.getCode(), null,
                messageVo.getFromUserRealName(), messageVo.getToUserRealName(), null, null);
    }

    /**
     * 将Set<String>类型对象转换为List<Message>类型对象
     *
     * @param stringSet 数据
     * @return 返回处理后的list
     */
    public List<Message> toMessageList(Set<String> stringSet, String fromUserAccount) {
        List<Message> messageList = new ArrayList<>();
        Iterator<String> iterator = stringSet.iterator();
        while (iterator.hasNext()) {
            String str = iterator.next();
            JSONObject jsonObject = JSON.parseObject(str);
            Message message = JSON.parseObject(String.valueOf(jsonObject), Message.class);
            if (fromUserAccount.equals(message.getFromUserAccount()) && message.getType().intValue() == MessageType.SYS_MSG.intValue()) {
                String content = message.getContent();
                if (!Strings.isNullOrEmpty(message.getFromUserRealName()) && content.contains(message.getFromUserRealName())) {
                    content = content.replaceAll(message.getFromUserRealName(), "你");
                }
                if (!Strings.isNullOrEmpty(message.getFromUserAccount()) && content.contains(message.getFromUserAccount())) {
                    content = content.replaceAll(message.getFromUserAccount(), "你");
                }
                message.setContent(content);
            }
            messageList.add(message);
        }
        return messageList;
    }

    /**
     * 将JSONObject对象转换为UserGroupMessage类型对象，JSONObject是从数据库中取出的格式（下划线）
     *
     * @param jsonObject
     * @return
     */
    public UserGroupMessage toUserGroupMessageFromTableFormat(JSONObject jsonObject) {
        UserGroupMessage userGroupMessage = new UserGroupMessage();
        userGroupMessage.setId(jsonObject.getInteger("id"));
        userGroupMessage.setUserGroupId(jsonObject.getInteger("user_group_id"));
        userGroupMessage.setFromUserAccount(jsonObject.getString("from_user_account"));
        userGroupMessage.setFromUserRealName(jsonObject.getString("from_user_real_name"));
        userGroupMessage.setContent(jsonObject.getString("content"));
        userGroupMessage.setType(jsonObject.getInteger("type_"));
        userGroupMessage.setFilePath(jsonObject.getString("file_path"));
        userGroupMessage.setFromUserAvailable(jsonObject.getInteger("from_user_available"));
        userGroupMessage.setFromUserUnavailableTime(jsonObject.getDate("from_user_unavailable_time"));
        userGroupMessage.setCreateTime(jsonObject.getDate("create_time"));
        userGroupMessage.setRetractionTime(jsonObject.getDate("retraction_time"));
        userGroupMessage.setRetractionContent(jsonObject.getString("retraction_content"));
        return userGroupMessage;
    }

    /**
     * 将JSONObject对象转换为ChatPair类型对象，JSONObject是从数据库中取出的格式（下划线）
     *
     * @param jsonObject jsonObject
     * @return 返回chatPair
     */
    public ChatPair toChatPairFromTableFormat(JSONObject jsonObject) {
        ChatPair chatPair = new ChatPair();
        chatPair.setId(jsonObject.getInteger("id"));
        chatPair.setFromUserAccount(jsonObject.getString("from_user_account"));
        chatPair.setToUserAccount(jsonObject.getString("to_user_account"));
        chatPair.setCode(jsonObject.getInteger("code_"));
        chatPair.setToppingTime(jsonObject.getDate("topping_time"));
        chatPair.setLastContactTime(jsonObject.getDate("last_contact_time"));
        chatPair.setContentInvisibleTime(jsonObject.getDate("content_invisible_time"));
        chatPair.setChatPageStatus(jsonObject.getInteger("chat_page_status"));
        chatPair.setNoReminder(jsonObject.getInteger("no_reminder"));
        return chatPair;
    }

    /**
     * 将JSONObject对象转换为Account类型对象，JSONObject是从数据库中取出的格式（下划线）
     *
     * @param jsonObject jsonObject
     * @return 返回Account
     */
    public Account toAccountFromTableFormat(JSONObject jsonObject) {
        Account account = new Account();
        account.setId(jsonObject.getString("id"));
        account.setRealName(jsonObject.getString("real_name"));
        account.setUsername(jsonObject.getString("username"));
        account.setDyjCode(jsonObject.getString("dyj_code"));
        account.setPinYin(jsonObject.getString("pin_yin"));
        account.setCapitalInitial(jsonObject.getString("capital_initial"));
        account.setDepartmentName(jsonObject.getString("department_name"));
        account.setMobile(jsonObject.getString("mobile"));
        account.setErp9Login(jsonObject.getInteger("erp9_login"));
        account.setLastErp9LoginTime(jsonObject.getDate("last_erp9_login_time"));
        account.setXlLogin(jsonObject.getInteger("xl_login"));
        account.setLastXlLoginTime(jsonObject.getDate("last_xl_login_time"));
        account.setRole(jsonObject.getInteger("role"));
        return account;
    }

    /**
     * 将JSONObject对象转换为RefGroupAccountOperation类型对象，JSONObject是从数据库中取出的格式（下划线）
     *
     * @param jsonObject jsonObject
     * @return 返回Account
     */
    public RefGroupAccountOperation toRefGroupAccountOperationFromTableFormat(JSONObject jsonObject) {
        RefGroupAccountOperation refGroupAccountOperation = new RefGroupAccountOperation();
        refGroupAccountOperation.setId(jsonObject.getInteger("id"));
        refGroupAccountOperation.setGroupId(jsonObject.getString("group_id"));
        refGroupAccountOperation.setAccountId(jsonObject.getString("account_id"));
        refGroupAccountOperation.setUsername(jsonObject.getString("username"));
        refGroupAccountOperation.setNoReminder(jsonObject.getInteger("no_reminder"));
        refGroupAccountOperation.setToppingTime(jsonObject.getDate("topping_time"));
        refGroupAccountOperation.setLastContactTime(jsonObject.getDate("last_contact_time"));
        refGroupAccountOperation.setContentInvisibleTime(jsonObject.getDate("content_invisible_time"));
        return refGroupAccountOperation;
    }

    /**
     * 将JSONObject对象转换为GroupMessageReceiver类型对象，JSONObject是从数据库中取出的格式（下划线）
     *
     * @param jsonObject jsonObject
     * @return 返回Account
     */
    public GroupMessageReceiver toGroupMessageReceiverFromTableFormat(JSONObject jsonObject) {
        GroupMessageReceiver groupMessageReceiver = new GroupMessageReceiver();
        groupMessageReceiver.setId(jsonObject.getInteger("id"));
        groupMessageReceiver.setGroupId(jsonObject.getString("group_id"));
        groupMessageReceiver.setGroupMessageId(jsonObject.getInteger("group_message_id"));
        groupMessageReceiver.setToUserAccount(jsonObject.getString("to_user_account"));
        groupMessageReceiver.setToUserRealName(jsonObject.getString("to_user_real_name"));
        groupMessageReceiver.setRead(jsonObject.getInteger("read_"));
        groupMessageReceiver.setReadTime(jsonObject.getDate("read_time"));
        groupMessageReceiver.setToUserAvailable(jsonObject.getInteger("to_user_available"));
        groupMessageReceiver.setToUserUnavailableTime(jsonObject.getDate("to_user_unavailable_time"));
        return groupMessageReceiver;
    }

    /**
     * 将JSONObject对象转换为RefUserGroupAccount类型对象，JSONObject是从数据库中取出的格式（下划线）
     *
     * @param jsonObject jsonObject
     * @return 返回Account
     */
    public RefUserGroupAccount toRefUserGroupAccountFromTableFormat(JSONObject jsonObject) {
        RefUserGroupAccount refUserGroupAccount = new RefUserGroupAccount();
        refUserGroupAccount.setId(jsonObject.getInteger("id"));
        refUserGroupAccount.setUserGroupId(jsonObject.getInteger("user_group_id"));
        refUserGroupAccount.setAccountId(jsonObject.getString("account_id"));
        refUserGroupAccount.setUsername(jsonObject.getString("username"));
        refUserGroupAccount.setNoReminder(jsonObject.getInteger("no_reminder"));
        refUserGroupAccount.setToppingTime(jsonObject.getDate("topping_time"));
        refUserGroupAccount.setLastContactTime(jsonObject.getDate("last_contact_time"));
        refUserGroupAccount.setContentInvisibleTime(jsonObject.getDate("content_invisible_time"));
        refUserGroupAccount.setJoinGroupTime(jsonObject.getDate("join_group_time"));
        return refUserGroupAccount;
    }

    /**
     * 将JSONObject对象转换为RefGroupAccount类型对象，JSONObject是从数据库中取出的格式（下划线）
     * @param jsonObject
     * @return
     */
    public RefGroupAccount toRefGroupAccountFromTableFormat(JSONObject jsonObject){
        RefGroupAccount refGroupAccount = new RefGroupAccount();
        refGroupAccount.setId(jsonObject.getInteger("id"));
        refGroupAccount.setGroupId(jsonObject.getString("group_id"));
        refGroupAccount.setAccountId(jsonObject.getString("account_id"));
        refGroupAccount.setUsername(jsonObject.getString("username"));
        return refGroupAccount;
    }

    /**
     * 将JSONObject对象转换为Dialogue类型对象，JSONObject是从数据库中取出的格式（下划线）
     *
     * @param jsonObject dataJsonObject
     * @return 返回Account
     */
    public Dialogue toDialogueFromTableFormat(JSONObject jsonObject) {
        Dialogue dialogue = new Dialogue();
        dialogue.setId(jsonObject.getInteger(("id")));
        dialogue.setAccountId(jsonObject.getString("account_id"));
        dialogue.setGroup(jsonObject.getString("group_"));
        dialogue.setToppingTime(jsonObject.getDate("topping_time"));
        dialogue.setContent(jsonObject.getString("content"));
        dialogue.setCreateTime(jsonObject.getDate("create_time"));
        dialogue.setUpdateTime(jsonObject.getDate("update_time"));
        return dialogue;
    }

    /**
     * 将JSONObject对象转换为RefUserGroupAccount类型对象，JSONObject是从数据库中取出的格式（下划线）
     *
     * @param jsonObject jsonObject
     * @return 返回Account
     */
    public UserGroupMessageReceiver toUserGroupMessageReceiverFromTableFormat(JSONObject jsonObject) {
        UserGroupMessageReceiver userGroupMessageReceiver = new UserGroupMessageReceiver();
        userGroupMessageReceiver.setId(jsonObject.getInteger("id"));
        userGroupMessageReceiver.setUserGroupId(jsonObject.getInteger("user_group_id"));
        userGroupMessageReceiver.setUserGroupMessageId(jsonObject.getInteger("user_group_message_id"));
        userGroupMessageReceiver.setToUserAccount(jsonObject.getString("to_user_account"));
        userGroupMessageReceiver.setToUserRealName(jsonObject.getString("to_user_real_name"));
        userGroupMessageReceiver.setRead(jsonObject.getInteger("read_"));
        userGroupMessageReceiver.setReadTime(jsonObject.getDate("read_time"));
        userGroupMessageReceiver.setToUserAvailable(jsonObject.getInteger("to_user_available"));
        userGroupMessageReceiver.setToUserUnavailableTime(jsonObject.getDate("to_user_unavailable_time"));
        return userGroupMessageReceiver;
    }

    /**
     * 将JSONObject对象转换为TreeNode类型对象，JSONObject是从数据库中取出的格式（下划线）
     * @param jsonObject jsonObject
     * @return 返回TreeNode
     */
    public TreeNode toTreeNodeFromTableFormat(JSONObject jsonObject) {
        TreeNode treeNode = new TreeNode();
        treeNode.setId(jsonObject.getString("id"));
        treeNode.setLabel(jsonObject.getString("label"));
        treeNode.setType(jsonObject.getInteger("type"));
        treeNode.setChildren(jsonObject.getString("children"));
        return treeNode;
    }

    /**
     * 将UserGroupMessageVo对象转换为UserGroupMessage对象
     *
     * @param userGroupMessageVo
     * @return
     */
    public UserGroupMessage toUserGroupMessage(UserGroupMessageVo userGroupMessageVo) {
        return new UserGroupMessage(null, userGroupMessageVo.getUserGroupId(), userGroupMessageVo.getFromUserAccount(), userGroupMessageVo.getContent(), userGroupMessageVo.getType(), userGroupMessageVo.getFilePath(), userGroupMessageVo.getFromUserRealName(), null, null);
    }

    /**
     * 将Set<String>类型对象转换为List<UserGroupMessage>类型对象
     *
     * @param stringSet
     * @return
     */
    public List<UserGroupMessage> toUserGroupMessageList(Set<String> stringSet, String fromUserAccount) {
        List<UserGroupMessage> userGroupMessageList = new ArrayList<>();
        Iterator<String> iterator = stringSet.iterator();
        while (iterator.hasNext()) {
            String str = iterator.next();
            JSONObject jsonObject = JSON.parseObject(str);
            UserGroupMessage userGroupMessage = JSON.parseObject(String.valueOf(jsonObject), UserGroupMessage.class);
            if (fromUserAccount.equals(userGroupMessage.getFromUserAccount()) && userGroupMessage.getType().intValue() == MessageType.SYS_MSG.intValue()) {
                String content = userGroupMessage.getContent();
                content = content.replaceAll(userGroupMessage.getFromUserRealName(), "你");
                userGroupMessage.setContent(content);
            }
            userGroupMessageList.add(userGroupMessage);
        }
        return userGroupMessageList;
    }

    /**
     * 将TreeNode对象转换为TreeNodePojo对象
     *
     * @param treeNode
     * @return
     */
    public TreeNodePojo toTreeNodePojo(TreeNode treeNode, List<String> sendMsgPermissionGroupIds, Boolean isAdmin) {
        if (null != treeNode) {
            TreeNodePojo treeNodePojo = new TreeNodePojo();
            treeNodePojo.setId(treeNode.getId());
            treeNodePojo.setLabel(treeNode.getLabel());
            treeNodePojo.setType(treeNode.getType());

            // 判断当前用户是否有操作当前群组权限
            if (isAdmin || sendMsgPermissionGroupIds != null && sendMsgPermissionGroupIds.size() > 0 && sendMsgPermissionGroupIds.contains(treeNode.getId())) {
                treeNodePojo.setSendMsgPermission(Boolean.TRUE);
            }

            if (null != treeNode.getChildren()) {
                String children = treeNode.getChildren();
                List<TreeNode> treeNodeList = JSONObject.parseArray(children, TreeNode.class);
                List<TreeNodePojo> resultNodeList = new ArrayList<TreeNodePojo>();
                for (int i = 0; i < treeNodeList.size(); i++) {
                    TreeNode node = treeNodeList.get(i);
                    TreeNodePojo nodePojo = new TreeNodePojo();
                    BeanUtils.copyProperties(node, nodePojo);

                    // 判断当前用户是否有操作当前群组权限
                    if (isAdmin || sendMsgPermissionGroupIds != null && sendMsgPermissionGroupIds.size() > 0 && sendMsgPermissionGroupIds.contains(nodePojo.getId())) {
                        nodePojo.setSendMsgPermission(Boolean.TRUE);
                    }

                    resultNodeList.add(nodePojo);
                }
                treeNodePojo.setChildren(resultNodeList);
            }
            return treeNodePojo;
        }
        return null;
    }


}